package cn.pa4j.quartz;

import cn.hutool.json.JSONObject;
import cn.pa4j.entity.Live;
import cn.pa4j.mapper.H2Mapper;
import cn.pa4j.utils.LiveUtil;
import cn.pa4j.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 060016 on 2019-3-15.
 */
@Component
public class TimeQuartz {

    @Autowired
    H2Mapper mapper;

    static Map<String, Boolean> isLiveMap = new HashMap<>();

    /**
     * 一分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkLives() {
        System.out.println("开始检查开播状态");
        List<String> rooms = mapper.getAllRooms();
        for (String roomId : rooms) {
            JSONObject data = LiveUtil.check(roomId);
            String title = data.getStr("title");
            String live_status = data.getStr("live_status");
            System.out.println("直播间"+roomId+("1".equals(live_status)?"已开播":"未开播"));
            System.out.println(live_status);
            Boolean isLive = isLiveMap.get(roomId);
            if (isLive == null) {
                isLive = false;
            }
            if ("1".equals(live_status)) {
                if (!isLive) {
                    List<Live> lives = mapper.getLivesByRoomId(roomId);
                    for (Live live : lives) {
                        send(roomId,live.getUserid(),title);
                    }
                }
                isLiveMap.put(roomId, true);
            } else {
                isLiveMap.put(roomId, false);
            }
        }
    }

    private void send(String roomID,String userid, String title) {
        System.out.println(userid);
        WxUtil.sendWithTemplet(roomID,userid,"直播间"+roomID+"开播啦","标题："+title+"https://live.bilibili.com/"+roomID);
    }


    public static void main(String[] args) {
//        String s = WxUtil.sendWithTemplet("oP0H950q-g5eLXy5CKjOcoyCj7U8", "直播间5085开播啦", "标题：今晚早睡");
//        System.out.println(s);
    }
}
